package com.tomorrowbbs.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.tomorrowbbs.domain.ForumArticleAttachment;
import com.tomorrowbbs.domain.ForumBoard;
import com.tomorrowbbs.domain.SysSetting;
import com.tomorrowbbs.domain.constants.Constants;
import com.tomorrowbbs.domain.dto.FileUploadDto;
import com.tomorrowbbs.domain.dto.SysSetting4AuditDto;
import com.tomorrowbbs.domain.enums.*;
import com.tomorrowbbs.exception.BusinessException;
import com.tomorrowbbs.mapper.ForumArticleAttachmentMapper;
import com.tomorrowbbs.utils.FileUtils;
import com.tomorrowbbs.utils.ImageUtils;
import com.tomorrowbbs.utils.StringTools;
import com.tomorrowbbs.utils.SysCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tomorrowbbs.mapper.ForumArticleMapper;
import com.tomorrowbbs.domain.ForumArticle;
import com.tomorrowbbs.service.IForumArticleService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 文章信息Service业务层处理
 * 
 * @author zjz
 * @date 2024-11-09
 */
@Service
public class ForumArticleServiceImpl implements IForumArticleService 
{
    @Autowired
    private ForumArticleMapper forumArticleMapper;
    @Autowired
    private ForumBoardServiceImpl forumBoardServiceImpl;
    @Autowired
    private ForumArticleAttachmentMapper forumArticleAttachmentMapper;
    @Autowired
    private UserInfoServiceImpl userInfoService;
    @Resource
    private ImageUtils imageUtils;

    @Resource
    private FileUtils fileUtils;
    /**
     * 查询文章信息
     * 
     * @param articleId 文章信息主键
     * @return 文章信息
     */
    @Override
    public ForumArticle selectForumArticleByArticleId(String articleId)
    {
        return forumArticleMapper.selectForumArticleByArticleId(articleId);
    }

    /**
     * 查询文章信息列表
     * 
     * @param forumArticle 文章信息
     * @return 文章信息
     */
    @Override
    public List<ForumArticle> selectForumArticleList(ForumArticle forumArticle)
    {
        return forumArticleMapper.selectForumArticleList(forumArticle);
    }

    /**
     * 新增文章信息
     * 
     * @param forumArticle 文章信息
     * @return 结果
     */
    @Override
    public int insertForumArticle(ForumArticle forumArticle)
    {
        return forumArticleMapper.insertForumArticle(forumArticle);
    }

    /**
     * 修改文章信息
     * 
     * @param forumArticle 文章信息
     * @return 结果
     */
    @Override
    public int updateForumArticle(ForumArticle forumArticle)
    {
        return forumArticleMapper.updateForumArticle(forumArticle);
    }

    /**
     * 批量删除文章信息
     * 
     * @param articleIds 需要删除的文章信息主键
     * @return 结果
     */
    @Override
    public int deleteForumArticleByArticleIds(String[] articleIds)
    {
        return forumArticleMapper.deleteForumArticleByArticleIds(articleIds);
    }

    /**
     * 删除文章信息信息
     * 
     * @param articleId 文章信息主键
     * @return 结果
     */
    @Override
    public int deleteForumArticleByArticleId(String articleId)
    {
        return forumArticleMapper.deleteForumArticleByArticleId(articleId);
    }

    @Override
    public int countForumArticles(ForumArticle forumArticle) {
        return forumArticleMapper.countForumArticles(forumArticle);
    }

    @Override
    public List<ForumArticle> selectArticlePageList(ForumArticle article) {
        return forumArticleMapper.selectArticlePageList(article);
    }

    /*
    阅读文章*/
    @Override
    public ForumArticle readArticle(String articleId){
        ForumArticle forumArticle = forumArticleMapper.selectForumArticleByArticleId(articleId);
        if(forumArticle == null){
            throw new BusinessException(ResponseCodeEnum.CODE_404);
        }
        if(ArticleStatusEnum.AUDIT.getStatus().equals(forumArticle.getStatus())){
            //更新数据
           forumArticleMapper.updateArticleCount(UpdateArticleCountTypeEnum.READ_COUNT.getType(), Constants.ONE, articleId);
        }

        return forumArticle;
    }

    //发表文章
    @Override
    public void postArticle(Boolean isAdmin, ForumArticle article, ForumArticleAttachment articleAttachment, MultipartFile cover, MultipartFile attachment) {
        resetBoardInfo(isAdmin,article);

        Date curDate = new Date();
        String articleId = StringTools.getRandomString(Constants.LENGTH_15);
        article.setArticleId(articleId);
        article.setPostTime(curDate);
        article.setLastUpdateTime(curDate);

        //图片上传
        if(cover != null){
            FileUploadDto fileUploadDto = fileUtils.uploadFile2Local(cover,Constants.FILE_FOLDER_IMAGE, FileUploadTypeEnum.ARTICLE_COVER);
            article.setCover(fileUploadDto.getLocalPath());
        }
        //附件
        if(attachment !=null){
            uploadAttachment(article,articleAttachment,attachment,false);
            article.setAttachmentType(ArticleAttachmentTypeEnum.HAVE_ATTACHMENT.getType());
        }else {
            article.setAttachmentType(ArticleAttachmentTypeEnum.NO_ATTACHMENT.getType());
        }
        //审核信息
        if(isAdmin){
            article.setStatus(ArticleStatusEnum.AUDIT.getStatus());
        }else {
            SysSetting4AuditDto auditDto = SysCacheUtils.getSysSetting().getAuditSetting();
            article.setStatus(auditDto.getPostAudit()?ArticleStatusEnum.NO_AUDIT.getStatus() : ArticleStatusEnum.AUDIT.getStatus());
        }
        //替换图片
        String content = article.getContent();
        if(!StringTools.isEmpty(content)){
            String month = imageUtils.resetImageHtml(content);
            String replaceMonth = "/"+month+"/";
            content = content.replace(Constants.FILE_FOLDER_TEMP,replaceMonth);
            article.setContent(content);
            String markdownContent = article.getMarkdownContent();
            if(!StringTools.isEmpty(markdownContent)){
                markdownContent=markdownContent.replace(Constants.FILE_FOLDER_TEMP,replaceMonth);
                article.setMarkdownContent(markdownContent);
            }
        }


        forumArticleMapper.insertForumArticle(article);

        //增加用户积分
        Long postIntegral = Long.valueOf(SysCacheUtils.getSysSetting().getPostSetting().getPostIntegral());
        if(postIntegral>0 && ArticleStatusEnum.AUDIT.equals(article.getStatus()));{
            userInfoService.updateUserIntegral(article.getUserId(),UserIntegralOperTypeEnum.POST_ARTICLE,UserIntegralChangeTypeEnum.ADD.getChangeType(), postIntegral);
        }



    }

    @Override
    public void checkArticle(boolean isAdmin, ForumArticle article) {

    }

    //校验导航
    private void resetBoardInfo(Boolean isAdmin,ForumArticle forumArticle){
        ForumBoard pBoard = forumBoardServiceImpl.selectForumBoardByBoardId(forumArticle.getPBoardId());
        if(pBoard ==null || pBoard.getPostType() == Constants.ZERO && !isAdmin){
            throw new BusinessException("一级板块不存在");
        }
        forumArticle.setPBoardName(pBoard.getBoardName());

        if (forumArticle.getBoardId() != null && forumArticle.getBoardId() != 0){
            ForumBoard board = forumBoardServiceImpl.selectForumBoardByBoardId(forumArticle.getBoardId());
            if (board==null || board.getPostType() == Constants.ZERO && !isAdmin){
                throw new BusinessException("二级板块不存在");
            }
            forumArticle.setBoardName(board.getBoardName());
        }else {
            forumArticle.setBoardId(0l);
            forumArticle.setBoardName("");
        }
    }

    //附件上传
    public void uploadAttachment(ForumArticle article,ForumArticleAttachment articleAttachment,MultipartFile file,Boolean isUpdate){
        Integer allowSizeMb = SysCacheUtils.getSysSetting().getPostSetting().getAttachmentSize();
        long allowSize = allowSizeMb * Constants.FILE_SIZE_1M;
        if(file.getSize() > allowSize){
            throw new BusinessException("附件大小不能超过"+allowSizeMb+"MB");
        }
        //修改
        if(isUpdate){

        }
        FileUploadDto fileUploadDto = fileUtils.uploadFile2Local(file,Constants.FILE_FOLDER_ATTACHMENT,FileUploadTypeEnum.ARTICLE_ATTACHMENT);

        articleAttachment.setFileId(StringTools.getRandomNumber(Constants.LENGTH_15));
        articleAttachment.setArticleId(article.getArticleId());
        articleAttachment.setFileName(fileUploadDto.getOriginalFileName());
        articleAttachment.setFilePath(fileUploadDto.getLocalPath());
        articleAttachment.setFileSize(file.getSize());
        articleAttachment.setDownloadCount(0l);
        articleAttachment.setFileType(AttachmentFileTypeEnum.ZIP.getType());
        articleAttachment.setUserId(article.getUserId());
        forumArticleAttachmentMapper.insertForumArticleAttachment(articleAttachment);

    }



}


















